var page = 1;
$(document).ready(function () {
    /**
     * 选中不同li标签调用不同接口显示不同dom
     */
    // getCoupon();
    $(".list-unstyled li").click(function () {
        page = 1;
        var liHtml = $(this).text();
        $("#activeName").html(liHtml);
        var clickedIndex = $(this).index();
        clickedIndex += 1;
        switch (liHtml) {
            case "下载历史":
                getDownHistory(page);
                $("#pagination").show();
                break;
            case "我的订单":
                orderPage(page);
                $("#pagination").show();
                //todo something...
                break;
            case "优惠券":
                $("#pagination").hide();
                couponList(1);
                break;
            case "我的收藏":
                $("#pagination").hide();
                collectList();
                break;
            default:
                $("#pagination").hide();
                showInfo();
        }
        $('.card-body').hide();
        $(".card-body:nth-child(" + clickedIndex + ")").show();
    });
    /**
     * 默认选中第一个
     */
    $(".list-unstyled li").eq(0).click();
});

/**
 * 格式化金钱
 * @param number
 * @returns {string}
 */
function formatMoney(number) {
    const formatter =  new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
    });

    return formatter.format(number);
}


function selectCoupon(){
    var htmlStr = [];
    var timestamp = Math.floor(new Date().getTime() / 1000);
    let token = localStorage.getItem(TOKEN)
    $.ajax({
        url: '/api/order/getCoupon', type: 'get', beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        }, async: false, dataType: 'json', success: function (r) {
            for (var i in r.data) {
                if(r.data[i].status == 1 && r.data[i].end > timestamp){
                    htmlStr[i] = `<a class="dropdown-item" href="javascript:useCoupon();">${r.data[i].title}</a>`
                }
            }
        }
    });
    return htmlStr;
}

/**
 * 查询订单是否能使用优惠券
 * @param orderId
 */
function getCanCoupon(orderId){
    let token =localStorage.getItem(TOKEN);
    $.ajax({
        url:'/api/order/canCouponList',
        type:'get',
        beforeSend:function (xhr){
            xhr.setRequestHeader("Authorization","Bearer "+token);
        },
        data:{orderId:orderId},
        async:false,
        dataType:'json',
        success:function(r){
            var canCouponHtml = '';
           if(r.code == 200){
               if(r.data.length > 0){
                   for(var i in r.data){
                       canCouponHtml+=`<li><a class="dropdown-item" data-id="${r.data[i].id}">${r.data[i].title}</a></li>`;
                   }
               }else{
                   canCouponHtml+=`<li><a class="dropdown-item" id="${r.data[i].id}">暂无可用优惠券</a></li>`;
               }
           }else{
                canCouponHtml+=`<li><a class="dropdown-item" id="${r.data[i].id}">暂无可用优惠券</a></li>`;
           }
            $("#downlist"+orderId).html(canCouponHtml);
            $(".dropdown-item").click(function(){
                if($(this).text() != '暂无可用优惠券'){
                    let id = $(this).data('id');
                    $("#topay"+orderId).data("coupon",id);
                    console.dir($("#topay"+orderId).data("coupon"));
                    $(".dropdown-item").removeClass("active");
                    $(this).addClass("active");
                    $("#downbutton"+orderId).html($(this).text());
                }
            })
        }
    })
}

/**
 * 取消订单
 * @param orderNo
 */
function cancelOrder(orderNo){
    let token = localStorage.getItem(TOKEN)
    $.ajax({
        url:'/api/order/cancel',
        type:'get',
        beforeSend:function (xhr){
            xhr.setRequestHeader("Authorization","Bearer "+token);
        },
        data:{order_no:orderNo},
        async:false,
        dataType:'json',
        success:function(r){
            if(r.code == 200){

            }
            orderPage(page);
        }
    });
}
/**
 * 订单列表
 * @param pageNum
 */
function orderPage(pageNum) {
    page = pageNum;
    let token = localStorage.getItem(TOKEN)
    $.ajax({
        url: '/api/member/orderList', type: 'get', beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        }, data: {page: pageNum, limit: 8}, async: false, dataType: 'json', success: function (r) {
            if (r.data.count <= 0) {
                var htmlStr = '<center><img src="/static/empty.png" style="margin-top:50px;width:250px;margin-bottom: 50px;"></center>';
            } else {
                var htmlStr = '';
                for (var i in r.data.data) {
                    if(r.data.data[i].status == 0){
                        var couponStr = ``;
                        // if(!r.data.data[i].member_coupon_id){
                        //    couponStr+=`
                        //              <div class="dropdown">
                        //                        <button type="button" class="couponButton btn btn-primary dropdown-toggle "
                        //                                data-bs-toggle="dropdown" data-id="${r.data.data[i].id}" id="downbutton${r.data.data[i].id}">
                        //                            选择优惠券
                        //                        </button>
                        //                        <div class="dropdown-menu coupon_list" id="downlist${r.data.data[i].id}">
                        //
                        //                        </div>
                        //              </div>`
                        // }
                        htmlStr+=`<div class="order_card">
                                    <div class="card_top">
                                        <div class="order_p">订单号：${r.data.data[i].order_no}</div>
                                        <div class="date">${r.data.data[i].created_at}</div>
                                        <div class="pay">
                                            <div class="close" onClick="cancelOrder('${r.data.data[i].order_no}')">取消订单</div>
                                            <div class="gotoPay" onClick="rePay('${r.data.data[i].order_no}','${r.data.data[i].pay_type}')" id="topay${r.data.data[i].id}" data-coupon="${r.data.data[i].member_coupon_id}">去支付</div>
                                        </div>
                                    </div>
                                    <div class="card_main">
                                        <div class="title">${r.data.data[i].title}</div>
                                        <div class="price"><span><span id="money${r.data.data[i].id}" style="margin-left:20px">${formatMoney(r.data.data[i].real_money/100)}</span></span>
                                        </div>`+couponStr+
                            `<div class="state" style="margin-left:30px;">未支付</div>
                                    </div>
                                </div>`;
                    }
                    if(r.data.data[i].status == 1){
                        htmlStr+=`<div class="order_card">
                                    <div class="card_top">
                                        <div class="order_p">订单号：${r.data.data[i].order_no}</div>
                                        <div class="date">${r.data.data[i].created_at}</div>
                                    </div>
                                    <div class="card_main">
                                        <div class="title">${r.data.data[i].title}</div>
                                        <div class="price"><span><span id="money${r.data.data[i].id}" style="margin-left:20px">${formatMoney(r.data.data[i].real_money/100)}</span></span>
                                        </div><div class="state" style="margin-left:30px;">已支付</div>
                                    </div>
                                </div>`;
                    }
                    if(r.data.data[i].status == 2){
                        htmlStr+=`<div class="order_card">
                                    <div class="card_top">
                                        <div class="order_p">订单号：${r.data.data[i].order_no}</div>
                                        <div class="date">${r.data.data[i].created_at}</div>
                                    </div>
                                    <div class="card_main">
                                        <div class="title">${r.data.data[i].title}</div>
                                        <div class="price"><span><span id="money${r.data.data[i].id}" style="margin-left:20px">${formatMoney(r.data.data[i].real_money/100)}</span></span>
                                        </div><div class="state" style="margin-left:30px;">已取消</div>
                                    </div>
                                </div>`;
                    }
                    if(r.data.data[i].status == 3){
                        htmlStr+=`<div class="order_card">
                                    <div class="card_top">
                                        <div class="order_p">订单号：${r.data.data[i].order_no}</div>
                                        <div class="date">${r.data.data[i].created_at}</div>
                                    </div>
                                    <div class="card_main">
                                        <div class="title">${r.data.data[i].title}</div>
                                        <div class="price"><span><i><span id="money${r.data.data[i].id}" style="margin-left:20px">${formatMoney(r.data.data[i].real_money/100)}</span></span>
                                        </div><div class="state" style="margin-left:30px;">已超时</div>
                              </div>
                        </div>`;
                    }
                }
                $app.pager('pagination', 'orderPage', '', pageNum, r.data.count, 8);
            }
            $("#orderList").html(htmlStr);
            // $(".couponButton").click(function(){
            //     var id =$(this).data('id');
            //     getCanCoupon(id);
            // });
        }
    });
}


/**
 * 获取我的收藏列表
 */
function collectList() {
    let token = localStorage.getItem(TOKEN)
    $.ajax({
        url: '/api/member/collectList', type: 'get', beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        }, async: false, dataType: 'json', success: function (r) {
            var htmlStr = '';
            if(r.data.length > 0){
                for (var i in r.data) {
                    htmlStr += `<div class="owl-item active" style="width: 190px;float:left; margin-right: 30px;">
                                    <div class="item">
                                        <div class="category-layout col-12">
                                            <div class="category-thumb">
                                                <div class="images-hover image">
                                                    <a href="/detail/${r.data[i].id}" target="_blank">
                                                        <img src="https://cdn.mihetong.com/${r.data[i].title_pic}"
                                                             style="width:190px"
                                                             alt="${r.data[i].title}"
                                                             title="${r.data[i].title}"
                                                             class="img-responsive m-auto">
                                                    </a>
                                                </div>
                                                <div class="caption text-center">
                                                    <center>
                                                        <h4 class="cat-title">
                                                            <a href="/detail/${r.data[i].id}" target="_blank">${r.data[i].title}</a>
                                                        </h4>
                                                        <div>
                                                            <a href="/detail/${r.data[i].id}" target="_blank" class="featured-category-btn">
                                                                查看详情</a>
                                                        </div>
                                                    </center>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>`;
                }
            }else{
                var htmlStr = '<center><img src="/static/empty.png" style="margin-top:50px;width:250px;margin-bottom: 50px;"></center>';
            }
            $("#collectList").html(htmlStr);
            $("#pagination").hide();
            // $app.pager('pagination','orderPage','',pageNum,r.data.count,8);
        }
    });
}

/**
 * 获取用户下载历史
 * @param pageNum
 */
function getDownHistory(pageNum) {
    page = pageNum;
    let token = localStorage.getItem(TOKEN)
    $.ajax({
        url: '/api/member/downloadList', type: 'get', beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        }, data: {page: pageNum, limit: 10, type: 1}, async: false, dataType: 'json', success: function (r) {
            var htmlStr = '';
            if(r.data.count > 0){
                $app.pager('pagination', 'getDownHistory', '', pageNum, r.data.count, 10);
                for (var i in r.data.data) {
                    htmlStr += `<div class="owl-item active" style="width: 190px;float:left; margin-right: 30px;">
                                    <div class="item">
                                        <div class="category-layout col-12">
                                            <div class="category-thumb">
                                                <div class="images-hover image">
                                                    <a href="/detail/` + r.data.data[i].id + `">
                                                        <img src="https://cdn.mihetong.com/` + r.data.data[i].title_pic + `"
                                                             style="width:190px"
                                                             alt="` + r.data.data[i].title + `"
                                                             title="` + r.data.data[i].title + `"
                                                             class="img-responsive m-auto">
                                                    </a>
                                                </div>
                                                <div class="caption text-center">
                                                    <center>
                                                        <h4 class="cat-title">
                                                            <a href="/detail/` + r.data.data[i].id + `">` + r.data.data[i].title + `</a>
                                                        </h4>
                                                        <div>
                                                            <a href="/detail/` + r.data.data[i].id + `" class="featured-category-btn">
                                                                查看详情</a>
                                                        </div>
                                                    </center>
                                                    <a href="#" class="btn btn-default d-none">Shop Now</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>`;
                }
                $("#pagination").show();
            }else{
                 htmlStr = '<center><img src="/static/empty.png" style="margin-top:50px;width:250px;margin-bottom: 50px;"></center>';
                 $("#pagination").hide();
            }
            $("#downList").html(htmlStr);
        }
    });
}

/**
 * 用户个人信息
 */
function showInfo() {
    let info = localStorage.getItem(INFO);
    if (info) {
        info = JSON.parse(info);
        $("#nickname").html(info.nickname);
        if (info.is_vip) {
            $("#is_vip").html("铂金会员");
            let token = localStorage.getItem(TOKEN);
            $.ajax({
                url: '/api/member/downNum', type: 'get', beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", "Bearer " + token);
                }, async: false, dataType: 'json', success: function (r) {
                    if (r.code == 200) {
                        if (info.final == 1) {
                            $("#up_button").hide();
                            $("#vip_date").html('永久会员' + '（剩余' + r.data.count + '特权）');
                        } else {
                            $("#vip_date").html(info.vip_date + '到期' + '（剩余' + r.data.count + '特权）');
                        }
                    } else {
                        $("#vip_date").html(info.vip_date + '到期' + '（剩余0特权）');
                    }
                    $("#vip_date").show();
                }
            });
        } else {
            $("#vip_date").hide();
            $("#up_button").show();
            $("#is_vip").html("普通用户");
        }

    } else {
        location.href = '/';
    }
}



/**
 * 获取优惠券列表
 */
function couponList(type) {
    let token = localStorage.getItem(TOKEN)
    $.ajax({
        url: '/api/order/getCoupon', type: 'get', beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        }, async: false, dataType: 'json', success: function (r) {
            if (r.code == 200) {
                if(r.data.length > 0 ){
                    let htmlStr = `<ul class="nav nav-tabs">
  <li class="nav-item">
    <a class="nav-link" aria-current="page" href="javascript:couponList(1);">待使用(<span id="wait_use_num">0</span>)</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="javascript:couponList(2);">已使用(<span id="use_num">0</span>)</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="javascript:couponList(3);">已过期(<span id="expire_num">0</span>)</a>
  </li>
</ul><div class="tab-panel">`;
                    var timestamp = Math.floor(new Date().getTime() / 1000);
                    var wait_use_num = 0;
                    var use_num = 0;
                    var expire_num = 0;
                    for (var i in r.data) {
                        if(r.data[i].status == 1 && r.data[i].end > timestamp){
                            wait_use_num++;
                        }else if(r.data[i].status == 2){
                            use_num++;
                        }else{
                            expire_num++;
                        }
                        switch (type) {
                            case 1:
                                if (r.data[i].status == 1) {
                                    var start_date = new Date(r.data[i].start*1000); // 将时间戳转换为毫秒，并创建一个新的 Date 对象
                                    var start_year = start_date.getFullYear(); // 获取年份
                                    var start_month = ("0" + (start_date.getMonth() + 1)).slice(-2); // 获取月份（注意月份是从0开始计数的）
                                    var start_day = ("0" + start_date.getDate()).slice(-2); // 获取日期
                                    var end_date = new Date(r.data[i].end *1000); // 将时间戳转换为毫秒，并创建一个新的 Date 对象
                                    var end_year = end_date.getFullYear(); // 获取年份
                                    var end_month = ("0" + (end_date.getMonth() + 1)).slice(-2); // 获取月份（注意月份是从0开始计数的）
                                    var end_day = ("0" + end_date.getDate()).slice(-2); // 获取日期
                                    htmlStr+=`<div class="tab-panel-item tab-active-coupon">
                                    <a href="javascript:;" class="jq22-flex">
                                        <div class="jq22-price-nub">
                                            <div class="jq22-digit">
                                                <h2><em>￥</em>${r.data[i].price/100}</h2>
                                            </div>
                                            <div class="jq22-full">
                                                <p>满${r.data[i].fill_price/100}元可用</p>
                                            </div>
                                        </div>
                                        <div class="jq22-flex-box">
                                            <h2>${r.data[i].title}</h2>
                                            <h3>${start_year}/${start_month}/${start_day}~${end_year}/${end_month}/${end_day}</h3>
                                             <button>未使用</button>
                                        </div>
                                    </a>
                                </div>`;
                                }
                                break;
                            case 2:
                                if (r.data[i].status == 2) {
                                    var start_date = new Date(r.data[i].start * 1000); // 将时间戳转换为毫秒，并创建一个新的 Date 对象
                                    var start_year = date.getFullYear(); // 获取年份
                                    var start_month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份（注意月份是从0开始计数的）
                                    var start_day = ("0" + date.getDate()).slice(-2); // 获取日期
                                    var end_date = new Date(r.data[i].end *1000); // 将时间戳转换为毫秒，并创建一个新的 Date 对象
                                    var end_year = date.getFullYear(); // 获取年份
                                    var end_month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份（注意月份是从0开始计数的）
                                    var end_day = ("0" + date.getDate()).slice(-2); // 获取日期
                                    htmlStr+=`<div class="tab-panel-item tab-active-coupon">
                                    <a href="javascript:;" class="jq22-flex">
                                        <div class="jq22-price-nub">
                                            <div class="jq22-digit">
                                                <h2><em>￥</em>${r.data[i].price/100}</h2>
                                            </div>
                                            <div class="jq22-full">
                                                <p>满${r.data[i].fill_price/100}元可用</p>
                                            </div>
                                        </div>
                                        <div class="jq22-flex-box">
                                            <h2>${r.data[i].title}</h2>
                                            <h3>${start_year}/${start_month}/${start_day}~${end_year}/${end_month}/${end_day}</h3>
                                             <button>已使用</button>
                                        </div>
                                    </a>
                                </div>`;
                                }
                                break;
                            default:
                                if (r.data[i].end < timestamp) {
                                    var start_date = new Date(r.data[i].start * 1000); // 将时间戳转换为毫秒，并创建一个新的 Date 对象
                                    var start_year = date.getFullYear(); // 获取年份
                                    var start_month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份（注意月份是从0开始计数的）
                                    var start_day = ("0" + date.getDate()).slice(-2); // 获取日期
                                    var end_date = new Date(r.data[i].end *1000); // 将时间戳转换为毫秒，并创建一个新的 Date 对象
                                    var end_year = date.getFullYear(); // 获取年份
                                    var end_month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份（注意月份是从0开始计数的）
                                    var end_day = ("0" + date.getDate()).slice(-2); // 获取日期
                                    htmlStr+=`<div class="tab-panel-item tab-active-coupon">
                                    <a href="javascript:;" class="jq22-flex">
                                        <div class="jq22-price-nub">
                                            <div class="jq22-digit">
                                                <h2><em>￥</em>${r.data[i].price/100}</h2>
                                            </div>
                                            <div class="jq22-full">
                                                <p>满${r.data[i].fill_price/100}元可用</p>
                                            </div>
                                        </div>
                                        <div class="jq22-flex-box">
                                            <h2>${r.data[i].fill_price}</h2>
                                            <h3>${start_year}/${start_month}/${start_day}~${end_year}/${end_month}/${end_day}</h3>
                                             <button>已过期</button>
                                        </div>
                                    </a>
                                </div>`;
                                }
                        }
                    }
                    htmlStr += `</div>`;
                    $("#couponList").html(htmlStr);
                    $("#expire_num").html(expire_num);
                    $("#wait_use_num").html(wait_use_num);
                    $("#use_num").html(use_num);
                    $(".nav-link").removeClass("active");
                    $(".nav-link").eq(type-1).addClass("active");
                }else{
                    var htmlStr= '<center><img src="/static/empty.png" style="margin-top:50px;width:250px;margin-bottom: 50px;"></center>';
                    $("#couponList").html(htmlStr);
                }
            }
        }
    });
}

function rePay(orderNo,type){
    let token = localStorage.getItem(TOKEN)
    if(type == 1){
        type ='wechat';
        location.href='/pay?order_no='+orderNo;
    }else{
        type  = 'alipay';
        $.ajax({
            url: "/api/order/repay",
            type: "POST",
            data:{
                order_no:orderNo,
                return_url:location.href,
                type:type,
                host:'',
                type_mode:'pcPay',
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                if(res.code == 200){
                        const div=document.createElement('divform');
                        div.innerHTML=res.data.data;
                        document.body.appendChild(div);
                        document.forms['alipay_submit'].acceptCharset='GBK';
                        document.forms['alipay_submit'].submit();
                }else{
                    layer.msg("唤起支付失败 请稍后重试");
                }
            }
        });
    }
}

